//
//  ZFContactViewController.m
//  HappilyLoan
//
//  Created by zainishenbian on 2017/3/25.
//  Copyright © 2017年 zongqingxiangqian. All rights reserved.
//

#import "ZFContactViewController.h"
/***********ios9以前通讯录的框架******************/
#import <AddressBook/AddressBook.h>
#import <AddressBookUI/AddressBookUI.h>
/************ios9通讯录的新框架*****************/
#import <Contacts/Contacts.h>
#import <ContactsUI/ContactsUI.h>
#import "ValuePickerView.h"
#import "ZFCityPickerView.h"
#import "ZFHeader.h"

#define IS_UP_IOS_9  [[UIDevice currentDevice].systemVersion floatValue] >= 9.0

@interface ZFContactViewController ()<ABPeoplePickerNavigationControllerDelegate,CNContactPickerDelegate,UITextViewDelegate>
{
    NSString *startTime;
    
    NSArray *rightButtonArray;
    
    ValuePickerView *pickerV;
    ZFCityPickerView *cityPickV;
    NSArray *kinRelationArray;
    NSArray *otherRelationArray;
    
    NSString *selectName;
    NSString *selectedPhone;
    UIButton *selectOpenAddressBookButton;//选中打开通讯录的按钮
    
    NSString *kinName;
    NSString *kinPhone;
    NSString *kinGeocoding;
    NSString *otherName;
    NSString *otherPhone;
    NSString *otherGeocoding;
}
@property (nonatomic,strong) AnimatingView *animation;
@property (nonatomic,strong) AlertBoxView *alertV;
@end

@implementation ZFContactViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"contactView"];
    self.navigationController.navigationBarHidden = NO;
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"contactView"];
}
- (void)submitStatu:(ReturnStatuBlock)block
{
    self.submitStatuBlock = block;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"紧急联系人";

    [self initData];
}
- (void)initData
{
    
//    _KinDetailAdress.text = @"请输入您的详细地址";
//    _otherDetailAdress.text = @"请输入您的详细地址";
    
    startTime = [ZFPulicAPI getCurrentTimestamp];
    
    _animation = [[AnimatingView alloc] init];
    
    _alertV = [[AlertBoxView alloc] init];
    [self.view addSubview:_alertV];

    //初始化数据
    rightButtonArray = @[_kinRelationButton,_kinOpenButton,_otherRelationButton,_otherOpenButton];
    
    pickerV = [ValuePickerView new];
    cityPickV = [ZFCityPickerView new];
    cityPickV.dataSource = @[@"1",@"1",@"1",@"1",@"1",@"1",@"1",@"1",@"1",@"1",@"1",@"1",@"1",@"1",@"1",@"1",@"1",@"1",@"1",@"1",@"1"];

    kinRelationArray = @[@"配偶",@"父母",@"兄弟",@"姐妹",@"子女"];
    otherRelationArray = @[@"同学",@"亲戚",@"同事",@"朋友",@"其他"];
    
    [_kinRelationButton addTarget:self action:@selector(kinSelectClick:) forControlEvents:UIControlEventTouchUpInside];
    [_kinOpenButton addTarget:self action:@selector(kinOpenAddressBookClick:) forControlEvents:UIControlEventTouchUpInside];
    [_otherRelationButton addTarget:self action:@selector(otherSelectClick:) forControlEvents:UIControlEventTouchUpInside];
    [_otherOpenButton addTarget:self action:@selector(otherOpenAddressBookClick:) forControlEvents:UIControlEventTouchUpInside];
    
    [_sureButton addTarget:self action:@selector(sureClick:) forControlEvents:UIControlEventTouchUpInside];
    
    //展示数据
    if (_contactArray.count) {
        
        for (int i = 0; i < _contactArray.count; i ++) {
            
            ZFContactInfoModal *modal = _contactArray[0];
            if (i == 0) {
                
                kinName = modal.contact_name;
                kinPhone = modal.contact_phone;
                kinGeocoding = @"null";
            }
            if (i == 1) {
                
                otherName = modal.contact_name;
                otherPhone = modal.contact_phone;
                otherGeocoding = @"null";
            }
        }
        [self showData];
    }


}
#pragma mark ———— show data
- (void)showData
{
    for (ZFContactInfoModal *modal in _contactArray) {
        
        if ([modal.contact_type integerValue] == 1) {
            
            [_kinRelationButton setTitle:kinRelationArray[[modal.contact_relation integerValue]-1] forState:UIControlStateNormal];
            [_kinOpenButton setTitle:[NSString stringWithFormat:@"%@ %@",modal.contact_name,modal.contact_phone] forState:UIControlStateNormal];
//            [_kinCityButton setTitle:modal.ad_path forState:UIControlStateNormal];
//            _KinDetailAdress.text = modal.detail_address;
        }
        if ([modal.contact_type integerValue] == 2) {
            
            [_otherRelationButton setTitle:otherRelationArray[[modal.contact_relation integerValue]-6] forState:UIControlStateNormal];
            [_otherOpenButton setTitle:[NSString stringWithFormat:@"%@ %@",modal.contact_name,modal.contact_phone] forState:UIControlStateNormal];
//            [_otherCityButton setTitle:modal.ad_path forState:UIControlStateNormal];
//            _otherDetailAdress.text = modal.detail_address;
        }
    }
}
#pragma mark ———— 调用系统通讯录
- (void)JudgeAddressBookPower {
    ///获取通讯录权限，调用系统通讯录
    [self CheckAddressBookAuthorization:^(bool isAuthorized , bool isUp_ios_9) {
        if (isAuthorized) {
            [self callAddressBook:isUp_ios_9];
        }else {
            NSLog(@"请到设置>隐私>通讯录打开本应用的权限设置");
        }
    }];
}
- (void)CheckAddressBookAuthorization:(void (^)(bool isAuthorized,bool isup_ios_9))block
{
    if (IS_UP_IOS_9) {
        
        CNContactStore *contactStore = [[CNContactStore alloc] init];
        if ([CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts] == CNAuthorizationStatusNotDetermined) {
            
            [contactStore requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
                
                if (error) {
                    NSLog(@"Error:%@",error);
                }
                else if (!granted)
                {
                    block(NO,YES);
                }
                else
                {
                    block(YES,YES);
                }
            }];
        }
        else if ([CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts] == CNAuthorizationStatusAuthorized){
            block(YES,YES);
        }
        else {
            NSLog(@"请到设置>隐私>通讯录打开本应用的权限设置");
        }
    }
    else
    {
        ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
        ABAuthorizationStatus authStatus = ABAddressBookGetAuthorizationStatus();
        if (authStatus == kABAuthorizationStatusNotDetermined)
        {
            ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (error)
                    {
                        NSLog(@"Error: %@", (__bridge NSError *)error);
                    }
                    else if (!granted)
                    {
                        
                        block(NO,NO);
                    }
                    else
                    {
                        block(YES,NO);
                    }
                });
            });
        }
        else if (authStatus == kABAuthorizationStatusAuthorized) {
            block(YES,NO);
        }
        else {
            NSLog(@"请到设置>隐私>通讯录打开本应用的权限设置");
        }
    }
}

- (void)callAddressBook:(BOOL)isUp_ios_9 {
    if (isUp_ios_9) {
        CNContactPickerViewController *contactPicker = [[CNContactPickerViewController alloc] init];
        contactPicker.delegate = self;
        contactPicker.displayedPropertyKeys = @[CNContactPhoneNumbersKey];
        [self presentViewController:contactPicker animated:YES completion:nil];
    }else {
        ABPeoplePickerNavigationController *peoplePicker = [[ABPeoplePickerNavigationController alloc] init];
        peoplePicker.peoplePickerDelegate = self;
        [self presentViewController:peoplePicker animated:YES completion:nil];
        
    }
}  
#pragma mark -- CNContactPickerDelegate
- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContactProperty:(CNContactProperty *)contactProperty {
    CNPhoneNumber *phoneNumber = (CNPhoneNumber *)contactProperty.value;
    [self dismissViewControllerAnimated:YES completion:^{
        /// 联系人
        NSString *nameText1 = [NSString stringWithFormat:@"%@%@",contactProperty.contact.familyName,contactProperty.contact.givenName];
        /// 电话
        NSString *phoneText2 = phoneNumber.stringValue;
        //        text2 = [text2 stringByReplacingOccurrencesOfString:@"-" withString:@""];
        NSLog(@"联系人：%@, 电话：%@",nameText1,phoneText2);
        if (selectOpenAddressBookButton == _kinOpenButton) {
            
            kinName = nameText1;
            kinPhone = phoneText2;
            [_kinOpenButton setTitle:[NSString stringWithFormat:@"%@ %@",nameText1,phoneText2] forState:UIControlStateNormal];
        }
        if (selectOpenAddressBookButton == _otherOpenButton) {
            
            otherName = nameText1;
            otherPhone = phoneText2;
            [selectOpenAddressBookButton setTitle:[NSString stringWithFormat:@"%@ %@",nameText1,phoneText2] forState:UIControlStateNormal];
        }
    }];
}
#pragma mark -- ABPeoplePickerNavigationControllerDelegate
- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController*)peoplePicker didSelectPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier {
    
    ABMultiValueRef valuesRef = ABRecordCopyValue(person, kABPersonPhoneProperty);
    CFIndex index = ABMultiValueGetIndexForIdentifier(valuesRef,identifier);
    CFStringRef value = ABMultiValueCopyValueAtIndex(valuesRef,index);
    CFStringRef anFullName = ABRecordCopyCompositeName(person);
    
    [self dismissViewControllerAnimated:YES completion:^{
        /// 联系人
        NSString *nameText1 = [NSString stringWithFormat:@"%@",anFullName];
        /// 电话
        NSString *phoneText2 = (__bridge NSString*)value;
        //        text2 = [text2 stringByReplacingOccurrencesOfString:@"-" withString:@""];
        NSLog(@"联系人：%@, 电话：%@",nameText1,phoneText2);
        if (selectOpenAddressBookButton == _kinOpenButton) {
            
            kinName = nameText1;
            kinPhone = phoneText2;
        }
        if (selectOpenAddressBookButton == _otherOpenButton) {
            
            otherName = nameText1;
            otherPhone = phoneText2;
        }
    }];
}
#pragma mark ———— textview delegate
//- (void)textViewDidBeginEditing:(UITextView *)textView
//{
//    if ([textView.text isEqualToString:@"请输入您的详细地址"])
//    {
//        textView.text = @"";
//    }
//}
//
//- (void)textViewDidEndEditing:(UITextView *)textView
//{
//    if (textView.text.length < 1)
//    {
//        textView.text = @"请输入您的详细地址";
//    }
//}

#pragma mark ———— button的点击事件
//直系关系选择
- (void)kinSelectClick:(UIButton *)button
{
    pickerV.dataSource = kinRelationArray;
    pickerV.pickerTitle = @"直属亲属关系";
    pickerV.valueDidSelect = ^(NSString *value) {
        
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        NSArray * stateArr = [value componentsSeparatedByString:@"/"];
        [button setTitle:stateArr[0] forState:UIControlStateNormal];
    };
    [pickerV show];
}
//打开通讯录（直系）
- (void)kinOpenAddressBookClick:(UIButton *)button
{
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    selectOpenAddressBookButton = button;
    [self JudgeAddressBookPower];
}
//选择城市（直系）
- (IBAction)kinChooseCity:(id)sender {
    
    UIButton *button = (UIButton *)sender;
    cityPickV.valueDidSelect = ^(NSString *locationStr, NSString *geocoding) {
        
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [button setTitle:locationStr forState:UIControlStateNormal];
        kinGeocoding = geocoding;
    };
    [cityPickV show];
}

//其他关系选择
- (void)otherSelectClick:(UIButton *)button
{
    pickerV.dataSource = otherRelationArray;
    pickerV.pickerTitle = @"其他联系人关系";
    pickerV.valueDidSelect = ^(NSString *value) {
        
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        NSArray * stateArr = [value componentsSeparatedByString:@"/"];
        [button setTitle:stateArr[0] forState:UIControlStateNormal];
    };
    [pickerV show];
}
//打开通讯录（其他）
- (void)otherOpenAddressBookClick:(UIButton *)button
{
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    selectOpenAddressBookButton = button;
    [self JudgeAddressBookPower];
}
//选择城市（其他）
- (IBAction)otherChooseCity:(id)sender {
    
    UIButton *button = (UIButton *)sender;
    cityPickV.valueDidSelect = ^(NSString *locationStr, NSString *geocoding) {
        
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [button setTitle:locationStr forState:UIControlStateNormal];
        otherGeocoding = geocoding;
    };
    [cityPickV show];
}

//确定,提交信息
- (void)sureClick:(UIButton *)button
{
    if ([self judgeSubmitInfo]) {
        
        NSMutableArray *contactArray = [NSMutableArray new];
        for (int i = 0; i < 2; i ++) {
            
            ZFContactInfoModal *infoModal = [ZFContactInfoModal new];
            infoModal.startTime = startTime;
            if (i == 0) {
                
                infoModal.ad_code = @"null";
                infoModal.ad_path = @"null";
                infoModal.contact_name = kinName;
                infoModal.contact_phone = kinPhone;
                infoModal.contact_relation =[self getSingleSubmit:kinRelationArray writeInfo:_kinRelationButton.titleLabel.text contactType:1];
                infoModal.contact_type = @"1";
                infoModal.detail_address = @"null";
                if (_contactArray) {
                    
                    ZFContactInfoModal *modal = _contactArray[0];
                    infoModal.urgent_info_id = modal.urgent_info_id;
                }
                else
                {
                    infoModal.urgent_info_id = @"null";
                }
            }
            if (i == 1) {
                infoModal.ad_code = @"null";
                infoModal.ad_path = @"null";
                infoModal.contact_name = otherName;
                infoModal.contact_phone = otherPhone;
                infoModal.contact_relation =[self getSingleSubmit:otherRelationArray writeInfo:_otherRelationButton.titleLabel.text contactType:2];
                infoModal.contact_type = @"2";
                infoModal.detail_address = @"null";
                if (_contactArray) {
                    
                    ZFContactInfoModal *modal = _contactArray[1];
                    infoModal.urgent_info_id = modal.urgent_info_id;
                }
                else
                {
                    infoModal.urgent_info_id = @"null";
                }
            }
            [contactArray addObject:infoModal];
        }
        
        [_animation startTheAnimation];
        [ZFApplyInfoHttpRequest requestSubmitContactInfo:contactArray sucessBlock:^(NSDictionary *dict) {
            
            [_animation stopTheAnimation];
            if ([dict[@"is_alert"] integerValue] == 1) {
                
                [_alertV appearAndDisappearAlertWithString:dict[@"msg"]];
            }
            if ([dict[@"code"] integerValue] == 1) {
                
                self.submitStatuBlock(1);
                [self.navigationController popViewControllerAnimated:YES];
            }
            else
            {
                self.submitStatuBlock(0);
            }
        } failureBlock:^(NSInteger failSign) {
            
            [_animation stopTheAnimation];
            [_alertV appearAndDisappearAlertWithString:@"网络连接失败"];
        }];
    }
}
#pragma mark ———— 判断提交信息
- (BOOL)judgeSubmitInfo
{
    for (UIButton *button in rightButtonArray) {
        
        if ([button.titleLabel.text rangeOfString:@"请"].location != NSNotFound) {
            
            [_alertV appearAndDisappearAlertWithString:@"信息不完善" ];
            return NO;
        }
    }
//    if (_KinDetailAdress.text.length <= 0 || _otherDetailAdress.text.length <= 0 || [_KinDetailAdress.text isEqualToString:@"请输入您的详细地址"] || [_otherDetailAdress.text isEqualToString:@"请输入您的详细地址"] ) {
//        
//        [_alertV appearAndDisappearAlertWithString:@"信息不完善"];
//        return NO;
//    }
    if ([kinPhone isEqualToString:otherPhone]) {
        
        [_alertV appearAndDisappearAlertWithString:@"亲~联系人电话号码不能相同哦"];
        return NO;
    }
    return YES;
}
- (NSString *)getSingleSubmit:(NSArray *)array writeInfo:(NSString *)writeStr contactType:(NSInteger)contactType
{
    int j = 0;
    if (contactType == 2) {
        
        j = 5;
    }
    for (int i = 0; i < array.count; i ++) {
        
        if ([array[i] isEqualToString:writeStr]) {
            
            NSLog(@"%d",i+1);
            return [NSString stringWithFormat:@"%d",i+j+1];
        }
    }
    return @"0";
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
